﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace crontab
{
    public partial class Enterface : Form
    {
        private string path = ""; // 
        private string file = "crontab.list";
        private string initText = "# Minute(0-59) Hour(0-23) DayOfMonth(1-3) Month(1-12) DayOfWeek(0-6)  Command\n";

        private string iniFile = "config.ini";
        private string iniContent = "autorun=no\r\nminimize=no\r\nhideonexit=yes";
        private bool iniAutorun = false;
        private bool iniMinimize = false;
        private bool iniHideOnExit = false;

        private bool isFirstCreate = true;
        private FormWindowState windowStateBeforeHide = FormWindowState.Normal;

        private Form mouseTicker = null;

        private string iniLine = "\r\n";

        private Form currentForm = null;

        public Enterface()
        {
            InitializeComponent();

            string path = Application.ExecutablePath;
            this.path = path.Substring(0, path.LastIndexOf('\\') + 1);
            this.file = this.path + this.file;
            if (File.Exists(this.iniFile))
            {
                iniContent = File.ReadAllText(iniFile).Replace("\r", "").ToLower();
            }
            else
            {
                File.WriteAllText(iniFile, iniContent);
            }
            string[] iniContents = iniContent.Split(new char[] { '\n' });
            foreach (string content in iniContents)
            {
                string[] kv = content.Split(new char[] { '=' }, 2);
                string key = kv[0].Trim();
                string value = "";
                if (kv.Length == 2)
                {
                    value = kv[1].Trim();
                }
                switch (key)
                {
                    case "autorun":
                        iniAutorun = value == "yes" ? true : false;
                        break;
                    case "minimize":
                        iniMinimize = value == "yes" ? true : false;
                        break;
                    case "hideonexit":
                        iniHideOnExit = value == "yes" ? true : false;
                        break;
                }
            }
        }

        private void Enterface_Load(object sender, EventArgs e)
        {
            if (File.Exists(this.file))
            {
                crontext.Text = File.ReadAllText(this.file);
                Crond.start();
                btnStopStart.Text = "Stop Cron";
                btnStopStart.Enabled = true;
            }
            else
            {
                crontext.Text = this.initText;
                File.WriteAllText(this.file, this.initText);
                btnStopStart.Enabled = false;
            }
            ckbAutorun.Checked = iniAutorun;
            ckbMinimize.Checked = iniMinimize;
            if (iniMinimize)
            {
                this.Hide();
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            if (isFirstCreate && iniMinimize)
            {
                base.Visible = false;
                isFirstCreate = false;
            }
            currentForm = this;
            base.OnActivated(e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            File.WriteAllText(this.file, crontext.Text);
            Crond.start();
            btnStopStart.Text = "Stop Cron";
            btnStopStart.Enabled = true;
        }

        private void btnStopStart_Click(object sender, EventArgs e)
        {
            if (btnStopStart.Text == "Stop Cron")
            {
                btnStopStart.Text = "Stoping...";
                btnStopStart.Enabled = false;
                Crond.stop();
                btnStopStart.Enabled = true;
                btnStopStart.Text = "Start Cron";
            }
            else
            {
                Crond.start();
                btnStopStart.Text = "Stop Cron";
            }
        }

        private void notifyClick()
        {
            if (currentForm.Visible)
            {
                windowStateBeforeHide = currentForm.WindowState;
                if (currentForm.WindowState == FormWindowState.Maximized)
                {
                    currentForm.WindowState = FormWindowState.Normal;
                }
                currentForm.Hide();
                currentForm.ShowInTaskbar = false;
            }
            else
            {
                currentForm.Show();
                currentForm.ShowInTaskbar = true;
                currentForm.WindowState = windowStateBeforeHide;
                currentForm.BringToFront();
            }
        }

        private void ckbMinimize_CheckedChanged(object sender, EventArgs e)
        {
            iniMinimize = ckbMinimize.Checked;
            //ckbMinimize.Checked = iniMinimize;
            buildIniContent();
        }

        private void ckbAutorun_CheckedChanged(object sender, EventArgs e)
        {
            iniAutorun = ckbAutorun.Checked;
            //ckbAutorun.Checked = iniAutorun;
            try
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (iniAutorun)
                {
                    key.SetValue("crontab", Application.ExecutablePath.ToLower());
                }
                else
                {
                    key.DeleteValue("crontab");
                }
                //MessageBox.Show(key.GetValue("crontab").ToString());
                key.Close();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            buildIniContent();
        }

        private void buildIniContent()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("autorun=" + (iniAutorun == true ? "yes" : "no") + iniLine);
            sb.Append("minimize=" + (iniMinimize == true ? "yes" : "no") + iniLine);
            sb.Append("hideonexit=" + (iniHideOnExit == true ? "yes" : "no") + iniLine);
            File.WriteAllText(iniFile, sb.ToString());
        }

        private void Enterface_Resize(object sender, EventArgs e)
        {
            crontext.Height = this.Height - 80;
        }

        private void Enterface_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (iniHideOnExit && e.CloseReason.ToString() == "UserClosing")
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void exitEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void notify_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            notifyClick();
        }

        private void btnMouseTicker_Click(object sender, EventArgs e)
        {
            if (mouseTicker == null)
            {
                mouseTicker = new MouseTicker(this);
            }
            mouseTicker.Show();
            currentForm = mouseTicker;
            this.Hide();
        }
        
    }
}
